/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright (c) 2012-2019. haiyi Inc.
 * pms All rights reserved.
 */

package com.xingbg.projectimpl.web.config;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p> </p>
 *
 * <pre> Created: 2019-12-04 11:05  </pre>
 * <pre> Project: pms  </pre>
 *
 * @author hlzhou
 * @version 1.0
 * @since JDK 1.8
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    @Getter
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static <T> T getBean(Class<T> clazz,String name){
        return context.getBean(name,clazz);
    }

    public static <T> List<T> getBeansForType(Class<T> clazz) {
        final Map<String, T> beansOfType = context.getBeansOfType(clazz);
        if (null == beansOfType || beansOfType.isEmpty()) {
            return Collections.emptyList();
        }
        return new ArrayList<>(beansOfType.values());
    }
}
